<template>
  <div class="filter-life-cycle consumption-container">
    <div class="flex-center table-top">
      <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
        <px-form-item style="display: none" label="厂区">
          <px-select
            v-model="queryParams.factory"
            placeholder="请选择厂区"
            clearable
            @change="
              getSystemOptions;
              getEquipOptions;
              getMaterialOptions;
            "
          >
            <px-option v-for="item in factoryOptions" :key="item.itemValue" :label="item.name" :value="item.itemValue" />
          </px-select>
        </px-form-item>
        <px-form-item label="科室">
          <px-select
            v-model="queryParams.className"
            disabled
            placeholder="请选择科室"
            @change="
              getSystemOptions;
              getEquipOptions;
              getMaterialOptions;
            "
          >
            <px-option v-for="item in depOptions" :key="item.itemValue" :label="item.name" :value="item.itemValue" />
          </px-select>
        </px-form-item>
        <!-- <px-form-item label="系统">
          <px-select
            v-model="queryParams.systemName"
            placeholder="请选择系统"
            clearable
            @change="
              getEquipOptions;
              getMaterialOptions;
            "
          >
            <px-option v-for="item in systemOptions" :key="item.code" :label="item.name" :value="item.code" />
          </px-select>
        </px-form-item> -->
        <px-form-item style="width: 310px !important" label="系统">
          <px-tree-select
            v-model="queryParams.systemName"
            clearable
            style="width: 100%"
            placeholder="请选择设备系统（树状图）"
            :props="defaultProps"
            filterable
            :data="systemList"
            check-strictly="true"
            :render-after-expand="false"
            collapse-tags
            collapse-tags-tooltip
            @change="treeChage"
          />
        </px-form-item>
        <px-form-item label="设备">
          <px-select v-model="queryParams.eqpId" filterable remote clearable placeholder="请选择设备">
            <px-option v-for="(item, index) in equipOptions" :key="index" :label="item" :value="item" />
          </px-select>
        </px-form-item>
        <px-form-item label="耗材名称">
          <px-select v-model="queryParams.type" filterable placeholder="请选择耗材名称" clearable>
            <px-option v-for="(item, index) in materialOptions" :key="index" :label="item" :value="item" />
          </px-select>
        </px-form-item>
        <div class="search-form-btn flexNowrap">
          <px-button type="primary" @click="handleQuery">查询</px-button>
          <px-button @click="resetQuery">重置</px-button>
        </div>
      </px-form>
    </div>
    <div ref="objectModelTableRef" v-loading="tableLoading" class="table-content">
      <px-table :data="tableData" size="small" border class="common-table" :header-cell-style="headerCellStyleFn" height="calc(100vh - 289px)">
        <px-table-column label="序号" width="60" align="center" fixed="left">
          <template #default="{ $index }">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
          </template>
        </px-table-column>
        <px-table-column prop="ffuCode" label="所属设备" fixed show-overflow-tooltip />
        <px-table-column prop="filterType" label="耗材名称" fixed min-width="60" show-overflow-tooltip />
        <px-table-column prop="filterCode" label="备件编码" fixed show-overflow-tooltip />
        <!-- <px-table-column prop="filterInstallDate" label="系统" fixed min-width="120" show-overflow-tooltip /> -->
        <px-table-column prop="filterSpc" label="规格型号" fixed min-width="120" show-overflow-tooltip />
        <px-table-column prop="filterMaker" label="品牌" fixed min-width="60" show-overflow-tooltip />
        <!-- <px-table-column prop="filterInstallDate" label="单位" fixed min-width="120" show-overflow-tooltip /> -->
        <px-table-column prop="filterNumber" label="数量" fixed min-width="60" show-overflow-tooltip />
        <!-- <px-table-column prop="lifecycle_predict" label="出库单号" fixed min-width="60" show-overflow-tooltip /> -->
        <px-table-column prop="filterInstallDate" label="开始使用时间" fixed min-width="120" show-overflow-tooltip />
        <px-table-column prop="filterNextInstallDate" label="结束使用时间" fixed min-width="120" show-overflow-tooltip />
        <px-table-column prop="lifecycle_act" label="实际使用时长" fixed min-width="60" show-overflow-tooltip />
        <px-table-column prop="lifecycle_exp" label="额定使用时长" fixed min-width="80" show-overflow-tooltip />
        <px-table-column prop="lifecycle_predict" label="预测使用时长" min-width="80" show-overflow-tooltip />
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-pagination"
        :total="total"
        @pagination="handleQuery"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
defineOptions({
  name: "GAS_OPERATION_FILTER_LIFE_CYCLE_RECORD"
});
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { useRoute } from "vue-router";
import {
  queryListByTypeCode,
  querySystemModelCondition,
  queryEqpList,
  queryFilterList,
  queryListPage,
  queryFilterListPage,
  queryListPagesparePartNew,
  listInstalledFiltersWATER,
  consumablelistInstalledDevices
} from "@/api/modules/operation";
import { useRouterStoreHook } from "@/store/modules/router";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";
import { querySystemSelect } from "@/api/equip/archive";
const defaultProps = {
  children: "children",
  label: "name",
  value: "code"
};
const route = useRoute();
const routerStore = useRouterStoreHook();
const factoryOptions = ref([]);
const total = ref(0);
const gap = 40;
const defaultHeight = 606;
const scrollbarHeight = ref<number>(defaultHeight);
const objectModelTableRef = ref<HTMLElement | null>(null);
const systemList = ref([]);
const handleSystemFocus = async () => {
  querySystemSelect({ factoryArea: "", className: queryParams.className }).then(res => {
    console.log(res[0].children[0].children);
    systemList.value = res[0].children;
  });
};
//获取厂区
const getFactoryOption = async () => {
  const params = { typeCode: "factoryArea" };
  factoryOptions.value = await queryListByTypeCode(params);
};
const depOptions = ref([]);
//获取科室
const getDepOption = async () => {
  const params = { typeCode: "className" };
  depOptions.value = await queryListByTypeCode(params);
};
const queryParams = reactive({
  factory: "",
  className: routerStore.subject,
  systemName: "",
  eqpId: "",
  type: "",
  pageNum: 1,
  pageSize: 20
});
// 递归解构
const fn = (arr, options = []) => {
  for (let i = 0; i < arr.length; i += 1) {
    if (Array.isArray(arr[i].children)) {
      if (arr[i].children.length > 0) {
        fn(arr[i].children, options);
      }
    } else {
      options.push(arr[i]);
    }
  }
  return options;
};
//查系统
const systemOptions = ref([]);
const getSystemOptions = async () => {
  const params = { factoryArea: queryParams.factory, className: queryParams.className };
  const res = await querySystemModelCondition(params);
  systemOptions.value = fn(res);
};
//查设备
const equipOptions = ref([]);
const treeChage = () => {
  getEquipOptions();
  getMaterialOptions();
};
const getEquipOptions = async () => {
  let systemCodes = [];
  if (queryParams.systemName) {
    systemCodes.push(queryParams.systemName);
  }
  const params = { className: queryParams.className, systemCode: queryParams.systemName };
  const res = await consumablelistInstalledDevices(params);
  console.log(res);
  equipOptions.value = res;
};
const remoteMethod = async query => {
  console.log(query);
  if (query) {
    let systemCodes = [];
    if (queryParams.systemName) {
      systemCodes.push(queryParams.systemName);
    }
    const params = { className: queryParams.className, systemCode: queryParams.systemName };
    const res = await consumablelistInstalledDevices(params);
    console.log(res);
    equipOptions.value = res;
  }
};
const materialOptions = ref([]);
//查耗材
const getMaterialOptions = async () => {
  // let systemCodes = [];
  // if (queryParams.systemName) {
  //   systemCodes.push(queryParams.systemName);
  // }

  // const res = await listInstalledFiltersWATER({});
  // materialOptions.value = res;
  let systemCodes = [];
  if (queryParams.systemName) {
    systemCodes.push(queryParams.systemName);
  }
  // const params = {
  //   category: "consumable",
  //   spareNameOrCode: "",
  //   typeCode: "",
  //   brandCode: "",
  //   modelCode: "",
  //   stockAlarm: false,
  //   supplyModel: "",
  //   className: queryParams.className,
  //   pageNum: 1,
  //   pageSize: 999
  // };
  // const res = await queryListPagesparePartNew(params);
  // materialOptions.value = res.data;

  const res = await listInstalledFiltersWATER({});
  materialOptions.value = res;
};

const tableData = ref([]);
// const total = ref(-1);
const tableLoading = ref(false);
const devTypeObj = {
  GAS: ["Unit"],
  WATER: ["RO", "SF", "UV", "TOC-UV", "UF", "CARBON", "RESIN", "MDG", "FP"],
  MACHINE: ["MAU", "NMAU", "AHU", "PCW"]
};
const handleQuery = async () => {
  //后台没有状态数据，传参去掉
  const devId = [];
  if (queryParams.eqpId) {
    devId.push(queryParams.eqpId);
  }
  const devType = devTypeObj[routerStore.subject];
  console.log(devType, "devType", routerStore.subject);
  let tableDataList = [];
  console.log(`output->queryParams`, queryParams);
  const params = {
    devId,
    type: queryParams.type,
    devTypes: devType,
    className: queryParams.className,
    systemCode: queryParams.systemName,
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize
  };
  const res = await queryFilterListPage(params);
  total.value = res.total;
  if (res.total > 0) {
    let filterList = res.data
      .map(v => {
        return v.filters;
      })
      .flat();
    tableDataList = [...filterList];
  }
  tableData.value = tableDataList;
};
const formRef = ref(null);
const resetQuery = () => {
  formRef.value.resetFields();
  queryParams.factory = "";
  queryParams.className = routerStore.subject;
  queryParams.systemName = "";
  queryParams.eqpId = "";
  queryParams.type = "";
  handleQuery();
};
onMounted(async () => {
  handleSystemFocus();
  if (route.query) {
    queryParams.eqpId = route.query.eqpId;
    queryParams.type = route.query.filterType;
    // if (route.query.className) {
    //   queryParams.className = route.query.className;
    // }
  }
  getFactoryOption();
  getDepOption();
  getSystemOptions();
  getEquipOptions();
  getMaterialOptions();
  handleQuery();
  await useUpdateDomHeight(scrollbarHeight, objectModelTableRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());

const headerCellStyleFn = () => {
  const style = {};
  style["background-color"] = "var(--px-color-primary-light-9) !important";
  return style;
};
</script>

<style lang="scss" scoped>
@import url("@/views/gas/consumption/scss/common.scss");

.filter-life-cycle {
  width: 100%;
  background-color: #fff;

  &-search {
    width: 100%;
  }

  .setContent-content-table {
    margin-top: 16px;
  }

  :deep(.px-form-item) {
    // width: 100%;
  }

  .flexNowrap {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
  }
}
</style>
